package com.hujf.netty.example.handle;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author Hujf
 * @title: HttpHandler
 * @date 2021/1/29 0029下午 10:09
 * @description: Http请求处理器
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //接收数据
        //判断数据是否为http
        if(msg instanceof HttpRequest){

            //Http 反馈
            HttpRequest httpRequest = (HttpRequest) msg;
            URI uri = new URI(httpRequest.getUri());
            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("不响应") ;

            }else{
                System.out.println(msg.getClass()+" "+ctx.channel().remoteAddress());
            //回复信息给浏览器 http 协议
            ByteBuf content = Unpooled.copiedBuffer("你好@hello w sh fuwu q h y lianjie ", CharsetUtil.UTF_8);

            //构造响应 http response
            FullHttpResponse  response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaders.Names.CONTENT_TYPE,"text/plain; charset=UTF-8");
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH,content.readableBytes());

            ctx.writeAndFlush(response);}
        }
    }
}
